package com.baitiaojun.api.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.util.Collections;

/**
 * @类名 JsonHttpMessageConverterConfig
 * @描述
 * @作者 白条君
 * @创建日期 2022/10/25 11:43
 * @版本 1.0
 */
@Configuration
public class JsonHttpMessageConverterConfig {

    @Bean
    public HttpMessageConverters httpMessageConverters() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.MapSortField,
                /**
                 * 禁止循环引用
                 * 循环引用就是一个对象在容器中添加了两次，fastjson发现前面有一次添加，
                 * 就会把前一次添加的引用地址和内容拿到后一次添加中
                 */
                SerializerFeature.WriteDateUseDateFormat
        );
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converter.setFastJsonConfig(config);
        return new HttpMessageConverters(converter);
    }
}
